package utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Vector;

public class DBConnectionPool {

	/**
	 * ***************************************************
	 * 
	 * Class DBConnectionPool
	 * 
	 * ****************************************************
	 */

	private int connections;
	private Vector freeConnections = new Vector();
	private int maxConn = 4;// set the max connection to 4
	private String dbUrl = "jdbc:mysql://localhost/test"; // Database
																				// URL
	private String dbUsername = "root";
	private String dbPassword = "19880103";

	public DBConnectionPool() {
		connections = 0;	
	}

	/*
	 * Free a Connection
	 */
	public synchronized void freeConnection(Connection con) {
		freeConnections.addElement(con);
		connections--;
		notifyAll();
	}

	/***
	 * Get a Connection From Connection Pool
	 * 
	 * @return Connection or null
	 */
	public synchronized Connection getConnection() {
		Connection con = null;

		if (freeConnections.size() > 0) {
			con = (Connection) freeConnections.firstElement();
			freeConnections.remove(0);
			try {
				if (con.isClosed()) {
					System.out.println("Delete a connection from pool");
					con = getConnection();
				}
			} catch (SQLException e) {
				System.out.println("Delete a connection from pool");
				con = getConnection();
			}

		} else if (maxConn == 0 || connections < maxConn) {
			con = newConnection();
		}
		// If get connection sucessfully
		if (con != null) {
			connections++;
		}
		return con;
	}

	/**
	 * Create a new connection
	 * 
	 * @return Connection
	 */
	private Connection newConnection() {
		Connection con = null;
		try {
		    
			//DriverManager.registerDriver(Class.forName("com.mysql.jdbc.Driver").newInstance(););
			con = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
			// System.out.println(" ");
		} catch (Exception ex) {
			System.out.println("Error connecting to database.  Machine Error: "
					+ ex.toString());
			ex.printStackTrace();
		}
		return con;
	}

	/**
	 * Close all the connections
	 */
	public synchronized void release() {
		Enumeration allConnections = freeConnections.elements();
		while (allConnections.hasMoreElements()) {
			Connection con = (Connection) allConnections.nextElement();
			try {
				con.close();
				System.out.println("Closing a conection from Connection poll");
			} catch (SQLException ex) {
				System.out.println("Can not close the connectoin");
				ex.printStackTrace();
			}
		}
	}

}
